package com.yunban.project.api.text_check.service.impl;

import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.service.AiCorrectionService;
import com.yunban.project.api.text_check.utils.SSEHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.module.support.redis.RedisService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: lijiajun
 * @date: 2025-03-03
 * @version: 1.0
 */
@Slf4j
@Service("deepSeekApplicationCorrectionService")
public class DeepSeekApplicationCorrectionService implements AiCorrectionService {

    @Resource
    private RedisService redisService;

    // 获取应用key
    public String getAppKey(CorrectionConfig config) {
        try {
            Long counterValue = redisService.incrementWithExpire("request_counter");
            List<String> botIds = config.getBotIds();
            if(CollectionUtils.isEmpty(botIds)){
                return config.getAppId();
            }
            // 根据计数值选择应用，botIds保证了循环分配
            // 减1是因为计数器从1开始
            int index = (counterValue.intValue() - 1) % botIds.size();
            return botIds.get(index);
        }catch (Exception ex){
            return config.getAppId();
        }
    }

    @Override
    public String correction(String text, CorrectionConfig config, String taskId) {
        String botAppKey = this.getAppKey(config);
//        String botAppKey = config.getBotId();
        String url = config.getUrlPath();
        try {
            CountDownLatch latch = new CountDownLatch(1);
            AtomicReference<String> resultHolder = new AtomicReference<>();
            SSEHandler.tencentSSEChat(url, text, botAppKey, taskId)
                    .subscribe(result -> {
                        resultHolder.set(result);
                        latch.countDown(); // 计数器减1，表示处理完成
                    }, error -> {
                        log.error("Error occurred: " + error.getMessage());
                        latch.countDown(); // 计数器减1，即使发生错误也要退出
                    });
            // 主线程等待异步处理完成
            latch.await();
            String result = resultHolder.get();
            if (!StringUtils.hasText(result)) {
                return null;
            }
            // 判断 result 中是否包含 “正确的表述应为：” 如果有，则取出 “正确的表述应为：”后的所有字符
            if (result.contains("正确的表述应为：")) {
                result = result.substring(result.indexOf("正确的表述应为：") + "正确的表述应为：".length());
                // 拼接统一响应String
                String resultFormat = "输出：%s分类：固定用法来源：/";
                return formatResponse(String.format(resultFormat, result, ""), text);
            }
            // 如果纠错后的输出格式中，不包含“输出：”“分类：”“来源：” 那么则跳过
            if (!result.contains("输出：") && !result.contains("分类：") && !result.contains("来源：")) {
                log.info("DeepSeek 纠正结果不包含\"输出：\"\"分类：\"\"来源：\"，跳过本次纠正");
                return null;
            }
            // 返回结果
            return formatResponse(result, text);
        } catch (InterruptedException e) {
            log.error("【DeepSeekApplicationCorrectionService.correction】Error occurred: " + e.getMessage());
            return null;
        }
    }
}
